﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Data.Activation;
using StyleMVVM.DependencyInjection;
using StyleMVVM.Logging;
#if NETFX_CORE
using Windows.UI.Xaml;

#else
using System.Windows;

#endif

namespace StyleMVVM.Module
{
	public sealed class ModuleManager : IActivationAware
	{
		private IEnumerable<IModule> modules;
		private static readonly string supplemental = typeof(ModuleManager).FullName;

		/// <summary>
		/// Register ModuleManager with DI container.
		/// </summary>
		/// <param name="container"></param>
		public static void RegisterExport(IDependencyInjectionContainer container)
		{
			container.Register(typeof(ModuleManager)).CoreExport(CoreExportStartOrder.UI).ImportMethod("ImportModules");
		}

		public void ImportModules(IEnumerable<IModule> modules)
		{
			this.modules = modules;
		}

		public void Activate()
		{
			if (modules != null)
			{
				List<Uri> uriList = new List<Uri>();

				foreach (IModule module in modules)
				{
					try
					{
						var uris = module.Initialize();

						if (uris != null)
						{
							uriList.AddRange(uris);
						}
					}
					catch (Exception exp)
					{
						Logger.Error("Exception thrown while initializing Module: " + module.GetType().FullName, supplemental, exp);
					}
				}

				if (Application.Current != null)
				{
					ResourceDictionary mergeDictionary = new ResourceDictionary();

					foreach (Uri uri in uriList)
					{
						try
						{
							mergeDictionary.MergedDictionaries.Add(new ResourceDictionary { Source = uri });
						}
						catch (Exception exp)
						{
							Logger.Error("Exception thrown when merging resource dictionary: " + uri.OriginalString, supplemental, exp);
						}
					}

					try
					{
						Application.Current.Resources.MergedDictionaries.Add(mergeDictionary);
					}
					catch (Exception exp)
					{
						Logger.Error("Excpetion thrown while loading merge dictionaries", supplemental, exp);
					}
				}
			}
		}
	}
}